

using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Abp.Linq;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.UI;
using Abp.Domain.Repositories;
using Abp.Domain.Services;

using Yozeev;
using Yozeev.BusinessLogic;
using Yozeev.SystemConfig;
using Yozeev.Models;
using Yozeev.Help;
using Abp.Domain.Entities.Auditing;

namespace Yozeev.BusinessLogic.DomainService
{
    /// <summary>
    /// ActivityTemp领域层的业务管理
    ///</summary>
    public class ActivityTempManager : CommonDomainService, IActivityTempManager
    {
		
		private readonly IRepository<ActivityTemp,Guid> _repository;
        private readonly IRepository<BranchUser, Guid> _branchUserRepository;
        private readonly IRepository<Customer, Guid> _customerRepository;
        private readonly IRepository<ActivityTempDetail, Guid> _activityDetailRepository;
        private readonly IRepository<Ticket, Guid> _ticketRepository;

        /// <summary>
        /// ActivityTemp的构造方法
        ///</summary>
        public ActivityTempManager(
			IRepository<ActivityTemp, Guid> repository
            , IRepository<BranchUser, Guid> branchUserRepository
            , IRepository<Customer, Guid> customerRepository
            , IRepository<ActivityTempDetail, Guid> activityDetailRepository
            , IRepository<Ticket, Guid> ticketRepository
            , IRepository<TicketDetail, Guid> ticketDetailRepository
        ) : base(branchUserRepository, customerRepository, ticketRepository, ticketDetailRepository)
        {
			_repository =  repository;
            _activityDetailRepository = activityDetailRepository;
        }


		/// <summary>
		/// 初始化
		///</summary>
		public void InitActivityTemp()
		{
			throw new NotImplementedException();
		}

        // TODO:编写领域业务代码


        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        public async Task<ActivityResultModel> CreateActivity(ActivityTemp activity)
        {
            ActivityResultModel activityResult = new ActivityResultModel()
            {
                ResultCode = "000",
                ResultMessage = "预定成功"
            };
            try
            {
                var customerId = activity.ActivityDetails.FirstOrDefault().Customer.Id;
                var customer = GetCustomersById(customerId);
                //activity赋值
                var _activityTemp = new ActivityTemp()
                {
                    Id = Guid.NewGuid(),
                    ActivityNo = CommonHelp.getVoucherNo(),
                    ActivityDate = DateTime.Today,
                    PlayDate = activity.ActivityDetails.FirstOrDefault().Schedule.SaleDate,
                    CustomerId = customerId,
                    Buyer = customer.CustomerName,
                    Mobile = customer.Mobile,
                    Remark = activity.Remark,
                    OpenId = activity.OpenId,
                    SourceId = activity.SourceId,
                    ScheduleId = activity.ScheduleId,
                    PayStatus = PayStatusEnum.NotPay,
                    OrderType = activity.OrderType,
                    PayMethodId = activity.PayMethodId,
                    VoucherNo = activity.VoucherNo,
                    TotalQuantity = activity.TotalQuantity,
                    TotalAmount = activity.TotalAmount,
                };
                if (activity.TravelAgencyId != null)
                    _activityTemp.TravelAgencyId = activity.TravelAgencyId;
                var createBranch = GetBranchUser((long)activity.CreatorUserId);
                CommonHelp.SetBranchId(_activityTemp, createBranch);
                await _repository.InsertAsync(_activityTemp);
                //遍历activityDetail
                var activityDetails = new List<ActivityTempDetail>();
                activity.ActivityDetails.ToList().ForEach(activityDetail => {
                    //获取票型
                    //var ticket = GetTicket(activityDetail.TicketPrice);
                    //创建订单明细
                    var _activityDetail = new ActivityTempDetail()
                    {
                        Id = Guid.NewGuid(),
                        ActivityTempId = _activityTemp.Id,
                        TicketPriceId = activityDetail.TicketPrice.Id,
                        TicketName = activityDetail.TicketPrice.TicketName,
                        SalePrice = activityDetail.TicketPrice.Price * activityDetail.TicketPrice.Discount,
                        Quantity = 1,
                        UniPrice = activityDetail.TicketPrice.Price,
                        Discount = activityDetail.TicketPrice.Discount,
                        TotalAmount = activityDetail.TicketPrice.Price * activityDetail.TicketPrice.Discount,
                        CustomerId = activityDetail.Customer.Id,
                        ScheduleId = activityDetail.Schedule.Id,
                    };
                    CommonHelp.SetBranchId(_activityDetail, createBranch);
                    _activityDetailRepository.Insert(_activityDetail);
                    activityDetails.Add(_activityDetail);
                });
                ActivityTemp temp = _activityTemp;
                temp.ActivityDetails = activityDetails;
                activityResult.Date = temp;
                return activityResult;
            }
            catch (Exception ex)
            {
                Logger.Error("CreateActivity预定", ex);
                throw ex;
            }
        }
        public ActivityResultModel CancelActivity(ActivityTemp activityTemp,long Collector)
        {
            ActivityResultModel activityResult = new ActivityResultModel()
            {
                ResultCode = "000",
                ResultMessage = "取消预订成功"
            };
            try
            {
                //判断是否可以提交
                if (activityTemp.PayStatus != PayStatusEnum.NotPay)
                    throw new Exception("该预留订单不是未支付状态");
                if (activityTemp.PayTime < DateTime.Now)
                    throw new Exception("已超过游玩时间，不能提交");
                var _activityTemp = _repository.GetAll().FirstOrDefault(m => m.Id == activityTemp.Id);
                _activityTemp.PayStatus = PayStatusEnum.PayStatusRefund;
                _activityTemp.PayTime = DateTime.Now;
                _activityTemp.Collector = Collector.ToString();
                _repository.UpdateAsync(_activityTemp);
                return activityResult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 根据ID获取预留订单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ActivityTemp GetActivityTempById(Guid Id)
        {
            var list = from activityTemp in _repository.GetAll().AsNoTracking()
                       where activityTemp.Id == Id
                       select new { activityTemp, activityTemp.Source, activityTemp.PayMethod, activityTemp.ActivityDetails }
                       ;
            var activityTempList = new List<ActivityTemp>();
            list.ToList().ForEach(t => {
                var ActivityTemp = t.activityTemp;
                ActivityTemp.Source = t.Source;
                ActivityTemp.PayMethod = t.PayMethod;
                ActivityTemp.ActivityDetails = t.ActivityDetails;
                activityTempList.Add(ActivityTemp);
            });
            return activityTempList.FirstOrDefault();
        }
        /// <summary>
        /// 根据支付凭证VoucherNo获取预留订单
        /// </summary>
        /// <param name="VoucherNo"></param>
        /// <returns></returns>
        public ActivityTemp GetActivityTempByVoucherNo(string VoucherNo)
        {
            var list = from activityTemp in _repository.GetAll().AsNoTracking()
                       where activityTemp.VoucherNo == VoucherNo
                       select new { activityTemp, activityTemp.Source, activityTemp.PayMethod, activityTemp.ActivityDetails }
                       ;
            var activityTempList = new List<ActivityTemp>();
            list.ToList().ForEach(t => {
                var ActivityTemp = t.activityTemp;
                ActivityTemp.Source = t.Source;
                ActivityTemp.PayMethod = t.PayMethod;
                ActivityTemp.ActivityDetails = t.ActivityDetails;
                activityTempList.Add(ActivityTemp);
            });
            return activityTempList.FirstOrDefault();
        }

        /// <summary>
        /// 根据订单ID获取预留订单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ActivityTemp GetActivityTempByActivityId(Guid ActivityId)
        {
            var list = from activityTemp in _repository.GetAll().AsNoTracking()
                       where activityTemp.ActivityId == ActivityId
                       select new { activityTemp, activityTemp.Source, activityTemp.PayMethod, activityTemp.ActivityDetails }
                       ;
            var activityTempList = new List<ActivityTemp>();
            list.ToList().ForEach(t => {
                var ActivityTemp = t.activityTemp;
                ActivityTemp.Source = t.Source;
                ActivityTemp.PayMethod = t.PayMethod;
                ActivityTemp.ActivityDetails = t.ActivityDetails;
                activityTempList.Add(ActivityTemp);
            });
            return activityTempList.FirstOrDefault();
        }
        /// <summary>
        /// 修改暂存订单凭证号
        /// </summary>
        /// <param name="activityTempId"></param>
        /// <param name="voucherNo"></param>
        /// <returns></returns>
        public async Task UpdateActivityTemp(Guid activityTempId, string voucherNo)
        {
            var entity = await _repository.GetAsync(activityTempId);
            entity.VoucherNo = voucherNo;
            await _repository.UpdateAsync(entity);
        }

        /// <summary>
        /// 修改暂存订单支付状态改为已关闭
        /// </summary>
        /// <param name="activityTempId"></param>
        /// <param name="voucherNo"></param>
        /// <returns></returns>
        public async Task UpdateActivityTempPayStatus(Guid activityTempId)
        {
            var entity = await _repository.GetAsync(activityTempId);
            entity.PayStatus = PayStatusEnum.PayStatusClose;
            await _repository.UpdateAsync(entity);
        }
    }
}
